<script setup lang="ts">
import { ref, shallowRef, onBeforeUnmount, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig, IToolbarConfig, Boot, IButtonMenu } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
// 引入 markdown 模块
import markdownModule from '@wangeditor/plugin-md'
import { saveCard as saveCardToStorage, getCard as getCardFromStorage } from '../services/cardService'
import type { CardItem } from '../types/cardData'
// 导入导航历史工具
import { getBackRouteName } from '../utils/navigation'
// 导入编辑器配置
import { getWangEditorConfig } from '../utils/editorConfig'
// 导入图标
import { Brush, Close, Check } from '@element-plus/icons-vue'
// 导入桶管理工具
import { getAllBuckets, getAllBucketNames } from '../utils/bucketManager'
// 导入外部链接处理工具
import { openExternalUrl } from '../utils/urlHandler'

// 获取i18n实例
const { t } = useI18n()

// 注册 markdown 插件
Boot.registerModule(markdownModule)

// 使用全局标志来防止多次注册相同菜单
const menuKey = 'myNotedToggleMdModeMenu'
// @ts-ignore - 全局变量，用于避免重复注册
if (!window.__NOTED_REGISTERED_MENUS__) {
  // @ts-ignore
  window.__NOTED_REGISTERED_MENUS__ = new Set()
}

// 检查菜单是否已经注册
// @ts-ignore
if (!window.__NOTED_REGISTERED_MENUS__.has(menuKey)) {
  // @ts-ignore
  window.__NOTED_REGISTERED_MENUS__.add(menuKey)
  
  Boot.registerMenu({
    key: menuKey,
    factory() {
      return {
        key: 'myNotedToggleMdMode',
        title: t('cardEditor.toggleMarkdown'),
        iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M896 192H128c-17.7 0-32 14.3-32 32v576c0 17.7 14.3 32 32 32h768c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zm-40 568H168V264h688v496z" /><path d="M360 384l-96 96 96 96v-72h304v72l96-96-96-96v72H360v-72z" /></svg>',
        tag: 'button',
        getValue() { return '' },
        isActive() { return false },
        isDisabled() { return false },
        exec(_editor: IDomEditor) { toggleEditorMode() } 
      } as IButtonMenu
    }
  })
}

// 自定义编辑器接口，扩展IDomEditor以支持Markdown
interface IMyEditor extends IDomEditor {
  getConfig(): IMyEditorConfig;
}

// 自定义编辑器配置接口，扩展IEditorConfig以支持Markdown
interface IMyEditorConfig extends IEditorConfig {
  markdownMode?: boolean;
}

// 路由
const router = useRouter()
const route = useRoute()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()

// 内容
const cardTitle = ref(t('cardEditor.untitledDoc'))
const bucketName = ref('')
const bucketOptions = ref<string[]>([]) // 桶名称选项列表
const cardContent = ref('')
const lastSavedContent = ref('')
const lastSavedTitle = ref(cardTitle.value)
const hasChanges = ref(false)
const isTitleFocused = ref(false)
const editorHasContent = ref(false)

// 显示的模式
const editorMode = ref<'normal' | 'markdown'>('normal')

// 切换编辑器模式
const toggleEditorMode = () => {
  editorMode.value = editorMode.value === 'normal' ? 'markdown' : 'normal'
  
  // 切换编辑器的 markdown 模式
  const editor = editorRef.value
  if (editor) {
    // 将编辑器转为自定义类型
    const myEditor = editor as IMyEditor
    const config = myEditor.getConfig()
    config.markdownMode = !config.markdownMode
  }
}

// 开始时间相关
const startTime = ref('')
const startTimePopoverVisible = ref(false)

// 标签相关
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tags = ref<string[]>([])
const tagColors = ref<Record<string, string>>({})
const inputTagRef = ref<any>(null)
const tagInputPlaceholder = ref(t('cardEditor.pleaseInputTitle'))
const currentEditingTagIndex = ref<number>(-1)
const colorPickerVisible = ref(false)
const selectedColor = ref('')
const customColorInput = ref('')
// 添加临时颜色状态用于实时预览
const tempTagColors = ref<Record<string, string>>({})
const tagColorOptions = ref([
  '#409EFF', // 蓝色
  '#67C23A', // 绿色
  '#E6A23C', // 黄色
  '#F56C6C', // 红色
  '#909399', // 灰色
  '#9B59B6', // 紫色
  '#1ABC9C', // 青绿色
  '#3498DB', // 天蓝色
  '#F39C12'  // 橙色
])

// 自动保存定时器
let autoSaveTimer: number | undefined = undefined

// 格式化日期时间
const formatDateTime = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 检查是否有未保存的更改
const checkChanges = () => {
  const editor = editorRef.value
  const contentChanged = editor ? editor.getHtml() !== lastSavedContent.value : false
  const titleChanged = cardTitle.value !== lastSavedTitle.value
  hasChanges.value = contentChanged || titleChanged
}

// 自动保存
const autoSave = async () => {
  const editor = editorRef.value
  if (!editor || !hasChanges.value) return
  
  const content = editor.getHtml()
  if (!content || content === `<p>${t('cardEditor.inputContent')}</p>`) return
  
  try {
    // 使用 electronAPI.getCurrentDateTime 获取统一格式的当前时间
    const now = await window.electronAPI.getCurrentDateTime('updated');
    const createdTime = !route.params.id ? await window.electronAPI.getCurrentDateTime('created') : undefined;
    
    // 确保 id 是字符串或 undefined
    const id = route.params.id ? 
      (Array.isArray(route.params.id) ? route.params.id[0] : route.params.id) : 
      undefined;
    
    // Create a plain object with only serializable data
    const cardData = {
      id: id, // 确保 id 是字符串或 undefined
      title: cardTitle.value.trim(),
      content: content,
      bucket: bucketName.value.trim(),
      tags: [...tags.value], // Create a new array to ensure it's clean
      tagColors: {...tagColors.value}, // 保存标签颜色信息
      markdown: editor.getText() || '',
      startTime: startTime.value || await window.electronAPI.getCurrentDateTime('start'), // 使用统一格式的开始时间
      updated: now,
      created: createdTime // 只有新卡片才设置创建时间
    }

    const updatedCard = await saveCardToStorage(cardData)
    
    lastSavedContent.value = content
    lastSavedTitle.value = cardTitle.value
    hasChanges.value = false
    
    // 如果是新卡片，更新路由到编辑模式
    if (!route.params.id && updatedCard.id) {
      router.replace(`/editor/${updatedCard.id}`)
    }
  } catch (error) {
    console.error('自动保存失败:', error)
    // 自动保存失败时不显示错误提示，避免打扰用户
    clearTimeout(autoSaveTimer)
    autoSaveTimer = window.setTimeout(autoSave, 5000) // 5秒后重试
  }
}

// 保存卡片
const saveCard = async (): Promise<CardItem | undefined> => {
  if (!cardTitle.value.trim()) {
    ElMessage.warning(t('cardEditor.pleaseInputTitle'))
    return
  }
  
  const editor = editorRef.value
  if (editor == null) return
  
  const content = editor.getHtml()
  if (!content || content === `<p>${t('cardEditor.inputContent')}</p>`) {
    ElMessage.warning(t('cardEditor.pleaseInputContent'))
    return
  }

  // 保存前显示加载状态
  const loading = ElLoading.service({
    lock: true,
    text: t('common.saving'),
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    // 使用 electronAPI.getCurrentDateTime 获取统一格式的当前时间
    const now = await window.electronAPI.getCurrentDateTime('updated');
    const createdTime = !route.params.id ? await window.electronAPI.getCurrentDateTime('created') : undefined;
    
    // 确保 id 是字符串或 undefined
    const id = route.params.id ? 
      (Array.isArray(route.params.id) ? route.params.id[0] : route.params.id) : 
      undefined;
    
    // Create a plain object with only serializable data
    const cardData = {
      id: id, // 确保 id 是字符串或 undefined
      title: cardTitle.value.trim(),
      content: content,
      bucket: bucketName.value.trim(),
      tags: [...tags.value], // Create a new array to ensure it's clean
      tagColors: {...tagColors.value}, // 保存标签颜色信息
      markdown: editor.getText() || '',
      startTime: startTime.value || await window.electronAPI.getCurrentDateTime('start'), // 使用统一格式的开始时间
      updated: now,
      created: createdTime // 只有新卡片才设置创建时间
    }

    const updatedCard = await saveCardToStorage(cardData)
    
    lastSavedContent.value = content
    lastSavedTitle.value = cardTitle.value
    hasChanges.value = false
    ElMessage.success(t('cardEditor.saveSuccess'))
    
    // 保存成功后跳转回首页
    router.push('/')
    
    return updatedCard
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(t('common.saveFailed'))
  } finally {
    loading.close()
  }
}

// 监听内容变化
const handleContentChange = () => {
  const editor = editorRef.value
  if (editor) {
    const html = editor.getHtml()
    editorHasContent.value = !!(html && html !== '<p></p>')
  }
  checkChanges()
  
  // 设置自动保存
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  autoSaveTimer = window.setTimeout(autoSave, 5000) // 5秒后自动保存
}

// 工具栏配置
const toolbarConfig = ref<Partial<IToolbarConfig>>({
  excludeKeys: []
})

// 设置 markdown 工具栏按钮
toolbarConfig.value.insertKeys = {
  index: 24,
  keys: ['myNotedToggleMdModeMenu'] // Changed to match the unique key we registered
}

// 获取编辑器配置
const baseEditorConfig = getWangEditorConfig()

// 编辑器配置
const editorConfig = ref<Partial<IEditorConfig>>({
  placeholder: '',  // 移除默认占位符，我们使用自定义的
  autoFocus: false,  // 让占位符能够正确显示
  MENU_CONF: baseEditorConfig.MENU_CONF,
  // 添加链接点击事件处理器
  EXTEND_CONF: {
    linkClickBehavior: (href: string) => {
      // 如果是http或https开头的链接，则使用外部浏览器打开
      if (href.startsWith('http://') || href.startsWith('https://')) {
        try {
          // 阻止默认行为
          event?.preventDefault();
          // 使用我们的工具函数打开外部链接
          openExternalUrl(href).catch(error => {
            console.error('打开外部链接失败:', error);
            ElMessage.error(t('cardEditor.openUrlFailed'));
          });
          return false; // 阻止编辑器默认行为
        } catch (error) {
          console.error('处理链接点击失败:', error);
        }
      }
      return true; // 对于其他链接使用默认行为
    }
  }
})

// 创建准备启用 markdown 的编辑器
editorConfig.value.hoverbarKeys = {
  text: {
    menuKeys: ['bold', 'italic', 'through', 'code', 'clearStyle']
  }
}

// 标签相关方法
const showTagInput = () => {
  // 重置当前编辑的标签索引
  currentEditingTagIndex.value = -1
  // 重置颜色选择为第一个选项
  selectedColor.value = tagColorOptions.value[0]
  // 重置自定义颜色输入
  customColorInput.value = ''
  // 重置临时颜色
  tempTagColors.value = {...tagColors.value}
  // 显示标签输入框
  tagInputVisible.value = true
  // 确保颜色选择器最初是关闭的
  colorPickerVisible.value = false
  
  nextTick(() => {
    inputTagRef.value?.input?.focus()
  })
}

const handleTagInputConfirm = () => {
  const inputValue = tagInputValue.value.trim()
  if (inputValue) {
    if (currentEditingTagIndex.value >= 0) {
      // 修改已有标签
      const oldTag = tags.value[currentEditingTagIndex.value]
      // 如果标签名称变化了，需要更新颜色映射
      if (oldTag !== inputValue) {
        // 保存旧标签的颜色
        const oldColor = tagColors.value[oldTag] || selectedColor.value || tagColorOptions.value[0]
        // 删除旧标签的颜色记录
        delete tagColors.value[oldTag]
        // 为新标签设置颜色
        if (!tags.value.includes(inputValue)) {
          tagColors.value[inputValue] = selectedColor.value || oldColor
        }
        // 更新标签文本
        tags.value[currentEditingTagIndex.value] = inputValue
      } else {
        // 标签名称没变，只更新颜色
        tagColors.value[oldTag] = selectedColor.value || tagColors.value[oldTag] || tagColorOptions.value[0]
      }
      hasChanges.value = true
    } else {
      // 新增标签
      // 检查是否已经存在相同标签
      if (!tags.value.includes(inputValue)) {
        // 检查标签数量是否超过3个
        if (tags.value.length < 3) {
          tags.value.push(inputValue)
          // 给新标签设置颜色
          tagColors.value[inputValue] = selectedColor.value || tagColorOptions.value[0]
          hasChanges.value = true
        } else {
          ElMessage.warning(t('cardEditor.maxTags'))
        }
      } else {
        ElMessage.warning(t('cardEditor.tagExists'))
      }
    }
  }
  
  // 重置状态
  tagInputVisible.value = false
  tagInputValue.value = ''
  colorPickerVisible.value = false
  currentEditingTagIndex.value = -1
  tempTagColors.value = {}
}

const handleTagClose = (index: number) => {
  const tagToRemove = tags.value[index]
  tags.value.splice(index, 1)
  // 移除对应的颜色记录
  if (tagColors.value[tagToRemove]) {
    delete tagColors.value[tagToRemove]
  }
  hasChanges.value = true
}

// 编辑标签
const editTag = (index: number) => {
  // 设置当前编辑的标签索引
  currentEditingTagIndex.value = index
  const tagToEdit = tags.value[index]
  // 设置输入框的值为标签文本
  tagInputValue.value = tagToEdit
  // 获取标签的颜色，如果没有则使用默认值
  selectedColor.value = tagColors.value[tagToEdit] || tagColorOptions.value[0]
  // 复制当前颜色到临时颜色
  tempTagColors.value = {...tagColors.value}
  // 显示标签输入框
  tagInputVisible.value = true
  // 确保颜色选择器最初是关闭的
  colorPickerVisible.value = false
  
  // 聚焦输入框
  nextTick(() => {
    inputTagRef.value?.input?.focus()
  })
}

// 显示颜色选择器
const showColorPicker = (event: MouseEvent) => {
  // 阻止事件冒泡，防止触发输入框的blur事件
  event.preventDefault()
  event.stopPropagation()
  
  // 显示颜色选择器
  colorPickerVisible.value = !colorPickerVisible.value
}

// 选择颜色
const selectColor = (color: string, event: MouseEvent) => {
  // 阻止事件冒泡
  event.preventDefault()
  event.stopPropagation()
  
  selectedColor.value = color
  
  // 实时预览：更新临时颜色
  if (currentEditingTagIndex.value >= 0) {
    const tagToEdit = tags.value[currentEditingTagIndex.value]
    tempTagColors.value[tagToEdit] = color
  }
  
  colorPickerVisible.value = false
  
  // 重新聚焦输入框
  nextTick(() => {
    inputTagRef.value?.input?.focus()
  })
}

// 验证是否为有效的HEX颜色代码
const isValidHexColor = (color: string): boolean => {
  const colorRegex = /^#([0-9A-F]{3}){1,2}$/i
  return !!color && colorRegex.test(color)
}

// 预览自定义颜色
const previewCustomColor = (value: string) => {
  // 可以添加额外的处理逻辑，目前主要通过模板绑定实时显示颜色
}

// 应用自定义颜色
const applyCustomColor = (event: MouseEvent | KeyboardEvent) => {
  // 阻止事件冒泡
  event.preventDefault()
  event.stopPropagation()
  
  // 验证是否为有效的颜色代码
  if (isValidHexColor(customColorInput.value)) {
    selectedColor.value = customColorInput.value
    
    // 实时预览：更新临时颜色
    if (currentEditingTagIndex.value >= 0) {
      const tagToEdit = tags.value[currentEditingTagIndex.value]
      tempTagColors.value[tagToEdit] = customColorInput.value
    }
    
    colorPickerVisible.value = false
    
    // 重新聚焦输入框
    nextTick(() => {
      inputTagRef.value?.input?.focus()
    })
  } else {
    ElMessage.warning(t('cardEditor.invalidColorCode') || '请输入有效的颜色代码 (如 #FF0000)')
  }
}

// 获取标签的颜色
const getTagColor = (tag: string) => {
  // 如果是当前编辑的标签且有临时颜色，使用临时颜色
  if (currentEditingTagIndex.value >= 0 && tags.value[currentEditingTagIndex.value] === tag && tempTagColors.value[tag]) {
    return tempTagColors.value[tag]
  }
  // 否则使用保存的颜色
  return tagColors.value[tag] || ''
}

// 确保颜色选择器点击外部区域时关闭
const closeColorPicker = (event: MouseEvent) => {
  if (colorPickerVisible.value) {
    // 检查点击的是否是颜色选择器外部
    const colorPickerEl = document.querySelector('.color-picker-container')
    const colorButtonEl = document.querySelector('.color-picker-button')
    if (colorPickerEl && !colorPickerEl.contains(event.target as Node) && 
        colorButtonEl && !colorButtonEl.contains(event.target as Node)) {
      colorPickerVisible.value = false
      
      // 重新聚焦输入框，但不自动保存
      nextTick(() => {
        inputTagRef.value?.input?.focus()
      })
    }
  }
}

// 初始加载卡片数据
const loadCardData = async () => {
  // 加载桶名称列表
  bucketOptions.value = getAllBucketNames();
  
  // 如果URL中有startTime参数，说明是从日历创建的，设置开始时间
  const queryStartTime = route.query.startTime;
  if (queryStartTime && typeof queryStartTime === 'string') {
    // 添加当前时间到日期中
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    startTime.value = `${queryStartTime} ${hours}:${minutes}`;
  } else if (!route.params.id) {
    // 如果没有startTime参数且不是编辑已有卡片，则是新创建的卡片
    // 默认设置当前系统时间为开始时间
    const now = new Date();
    startTime.value = formatDateTime(now);
  }

  // 加载已有卡片的信息（编辑模式）
  if (route.params.id) {
    try {
      const cardId = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id;
      const card = await getCardFromStorage(cardId) // Use string ID directly
      if (card) {
        cardTitle.value = card.title
        cardContent.value = card.content
        bucketName.value = card.bucket || '' // 加载桶名称
        tags.value = card.tags
        // 加载标签颜色信息
        if (card.tagColors) {
          tagColors.value = {...card.tagColors}
        }
        // 如果没有从URL获取到startTime，则使用卡片中的startTime
        if (!startTime.value) {
          startTime.value = card.startTime || ''
        }
        lastSavedTitle.value = card.title
        lastSavedContent.value = card.content
        editorHasContent.value = true
      }
    } catch (error) {
      console.error('加载卡片失败:', error)
      ElMessage.error(t('common.loadFailed'))
    }
  }
}

// 在组件挂载时设置一些初始行为
onMounted(() => {
  loadCardData()
  
  // Set focus with a slight delay to ensure placeholder displays correctly
  setTimeout(() => {
    const editor = editorRef.value
    if (editor) {
      // Only focus when there's content to avoid interfering with placeholder
      if (editor.getHtml() && editor.getHtml() !== '<p></p>') {
        editor.focus()
      }
    }
  }, 300)
  
  // Set beforeunload event listener for unsaved changes prompt
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // Add click outside event listener for color picker
  document.addEventListener('mousedown', closeColorPicker)
  
  // When window resize happens, make sure header stays hidden
  const ensureHeaderHidden = () => {
    // Force the route to be recognized as editor to keep header hidden
    const appHeader = document.querySelector('.app-header')
    if (appHeader && window.getComputedStyle(appHeader).display !== 'none') {
      (appHeader as HTMLElement).style.display = 'none'
    }
  }
  
  // Add event listener for resize
  window.addEventListener('resize', ensureHeaderHidden)
  
  // Run once on mount
  ensureHeaderHidden()
  
  // Cleanup function to remove the event listener
  onBeforeUnmount(() => {
    window.removeEventListener('resize', ensureHeaderHidden)
  })
})

// 处理离开页面前的提示
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  if (hasChanges.value) {
    e.preventDefault()
    e.returnValue = t('cardEditor.unsavedChanges')
    return e.returnValue
  }
}

// 组件销毁时的清理
onBeforeUnmount(() => {
  // 清除编辑器
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
  
  // 清除自动保存计时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  
  // 移除事件监听器
  window.removeEventListener('beforeunload', handleBeforeUnload)
  document.removeEventListener('mousedown', closeColorPicker)
})

// 编辑器创建完成的回调
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
  // 设置编辑器内容变化的监听
  editor.on('change', handleContentChange)
}

// 全屏编辑
const isFullscreen = ref(false)
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  
  if (isFullscreen.value) {
    document.documentElement.requestFullscreen().catch((err) => {
      console.error(t('cardEditor.fullscreenError'), err)
    })
  } else {
    if (document.fullscreenElement) {
      document.exitFullscreen().catch((err) => {
        console.error(t('cardEditor.exitFullscreenError'), err)
      })
    }
  }
}

// 取消编辑
const cancelEdit = () => {
  if (hasChanges.value) {
    ElMessageBox.confirm(
      t('cardEditor.confirmCancel'),
      t('common.confirm'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }
    ).then(() => {
      goBack();
    }).catch(() => {
      // 用户取消操作
    })
  } else {
    goBack();
  }
}

// 在标题获得焦点时
const handleTitleFocus = () => {
  isTitleFocused.value = true
  // 如果是默认标题则清空
  if (cardTitle.value === t('cardEditor.untitledDoc')) {
    cardTitle.value = ''
  }
}

// 在标题失去焦点时
const handleTitleBlur = () => {
  isTitleFocused.value = false
  // 如果标题为空则恢复默认
  if (!cardTitle.value.trim()) {
    cardTitle.value = t('cardEditor.untitledDoc')
  }
  
  checkChanges()
}

// 处理桶名称变化
const handleBucketChange = (value: string) => {
  if (value && !bucketOptions.value.includes(value)) {
    // 如果是新的桶名称，添加到列表中
    bucketOptions.value.push(value);
    // 可以选择持久化存储这个新桶名称
    import('../utils/bucketManager').then(module => {
      module.addBucket(value);
    });
  }
  
  hasChanges.value = true;
}

// 保存并返回
const saveAndReturn = async () => {
  const savedCard = await saveCard();
  if (savedCard) {
    goBack();
  }
};

// 返回上一页
const goBack = () => {
  const backRouteName = getBackRouteName();
  router.push({ name: backRouteName });
};

// handleBlur方法 - 添加新方法处理输入框失焦事件
const handleBlur = (event: FocusEvent) => {
  // 检查焦点是否移动到了颜色选择器相关元素上
  const colorPickerEl = document.querySelector('.color-picker-container')
  const colorButtonEl = document.querySelector('.color-picker-button')
  const submitButtonEl = document.querySelector('.input-buttons')
  
  // 如果焦点移动到了这些元素上，则不关闭输入框
  if ((colorPickerEl && colorPickerEl.contains(event.relatedTarget as Node)) ||
      (colorButtonEl && colorButtonEl.contains(event.relatedTarget as Node)) ||
      (submitButtonEl && submitButtonEl.contains(event.relatedTarget as Node))) {
    return
  }
  
  // 如果颜色选择器是打开的，也不关闭输入框
  if (colorPickerVisible.value) {
    return
  }
  
  // 否则，取消编辑，重置状态
  tagInputVisible.value = false
  tagInputValue.value = ''
  colorPickerVisible.value = false
  currentEditingTagIndex.value = -1
  tempTagColors.value = {}
}
</script>

<template>
  <div class="card-editor-container" :class="{ 'fullscreen': isFullscreen }">
    <!-- 顶部工具栏 -->
    <div class="editor-header">
      <div class="header-left">
        <el-button 
          @click="cancelEdit" 
          icon="ArrowLeft" 
          circle 
          plain 
          :title="t('common.back')"
          class="back-button"
        />
        
        <div class="title-container" :class="{ 'title-focused': isTitleFocused }">
          <input
            class="title-input"
            v-model="cardTitle"
            @focus="handleTitleFocus"
            @blur="handleTitleBlur"
          />
        </div>
        
        <!-- 添加桶名称选择框 -->
        <div class="bucket-container">
          <el-select 
            v-model="bucketName" 
            :placeholder="t('cardEditor.bucketName')"
            class="bucket-select"
            filterable
            allow-create
            default-first-option
            @change="handleBucketChange"
          >
            <el-option
              v-for="item in bucketOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </div>
      
      <div class="header-right">
        <div class="start-time-container">
          <el-tooltip :content="t('homepage.startTime')" placement="bottom">
            <el-button
              icon="Calendar"
              size="small"
              circle
              plain
              @click="startTimePopoverVisible = !startTimePopoverVisible"
              :type="startTime ? 'primary' : 'default'"
            />
          </el-tooltip>
          
          <el-popover
            v-model:visible="startTimePopoverVisible"
            trigger="click"
            placement="bottom"
            :width="340"
            @click.stop
          >
            <template #reference>
              <!-- Always have a valid element for the reference slot -->
              <span class="start-time-display" v-if="startTime">{{ startTime }}</span>
              <span class="start-time-placeholder" v-else></span>
            </template>
            
            <div class="date-time-picker-container">
              <p class="date-time-title">{{ t('homepage.startTime') }}</p>
              <el-date-picker
                v-model="startTime"
                type="datetime"
                :placeholder="t('homepage.startTime')"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :clearable="true"
                @change="startTimePopoverVisible = false"
              />
            </div>
          </el-popover>
        </div>
        
        <span class="save-status">
          {{ hasChanges ? t('cardEditor.editing') : t('cardEditor.saved') }}
        </span>
        
        <el-tooltip :content="t('cardEditor.toggleMarkdown')" placement="bottom">
          <el-button 
            @click="toggleEditorMode" 
            :type="editorMode === 'markdown' ? 'primary' : 'default'"
            size="small"
            icon="Edit"
            circle
            plain
          />
        </el-tooltip>
        
        <el-tooltip :content="t('cardEditor.fullscreen')" placement="bottom">
          <el-button
            @click="toggleFullscreen"
            size="small"
            :icon="isFullscreen ? 'FullScreen' : 'ZoomIn'"
            circle
            plain
          />
        </el-tooltip>
        
        <el-button type="primary" @click="saveAndReturn" size="small">{{ t('common.save') }}</el-button>
      </div>
    </div>
    
    <!-- 编辑器工具栏 -->
    <div class="editor-toolbar">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
        class="custom-toolbar"
      />
    </div>
    
    <!-- 编辑器主体 -->
    <div class="editor-body">
      <div class="placeholder-arrow" v-if="!editorHasContent">
        <span class="arrow-text">{{ t('cardEditor.inputContent') }}</span>
        <span class="cursor-placeholder">|</span>
      </div>
      <Editor
        v-model="cardContent"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
        class="custom-editor"
      />
    </div>
    
    <!-- 标签区域 -->
    <div class="tags-container">
      <div class="tags-label">{{ t('cardEditor.tags') }}:</div>
      <div class="tags-content">
        <el-tag
          v-for="(tag, index) in tags"
          :key="index"
          class="tag-item"
          closable
          :disable-transitions="false"
          @close="handleTagClose(index)"
          :style="getTagColor(tag) ? {backgroundColor: getTagColor(tag) + '33', borderColor: getTagColor(tag), color: getTagColor(tag)} : {}"
          @click="editTag(index)"
        >
          {{ tag }}
        </el-tag>
        
        <el-input
          v-if="tagInputVisible"
          ref="inputTagRef"
          v-model="tagInputValue"
          class="tag-input"
          size="small"
          :placeholder="tagInputPlaceholder"
          @keyup.enter="handleTagInputConfirm"
          @blur="handleBlur"
        >
          <template #append>
            <div class="input-buttons">
              <el-button @click="showColorPicker($event)" type="info" plain class="color-picker-button">
                <el-icon>
                  <Brush v-if="!colorPickerVisible" />
                  <Close v-else />
                </el-icon>
              </el-button>
              <el-button @click="handleTagInputConfirm" type="primary" plain>
                <el-icon><Check /></el-icon>
              </el-button>
            </div>
          </template>
        </el-input>
        
        <div v-if="colorPickerVisible" class="color-picker-container">
          <div class="color-options">
            <div 
              v-for="(color, index) in tagColorOptions" 
              :key="index" 
              class="color-option" 
              :style="{backgroundColor: color}" 
              :class="{'selected': selectedColor === color}"
              @click="selectColor(color, $event as MouseEvent)"
            ></div>
          </div>
          <div class="custom-color-input">
            <el-input 
              v-model="customColorInput" 
              size="small" 
              placeholder="#RRGGBB"
              @input="previewCustomColor"
              @keyup.enter="applyCustomColor"
            >
              <template #prepend>
                <div 
                  class="color-preview" 
                  :style="{ backgroundColor: isValidHexColor(customColorInput) ? customColorInput : 'transparent' }"
                ></div>
              </template>
              <template #append>
                <el-button @click="applyCustomColor" type="primary" plain>
                  <el-icon><Check /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
        
        <el-button
          v-else-if="tags.length < 3"
          class="button-new-tag"
          size="small"
          @click="showTagInput"
        >
          {{ t('cardEditor.addTag') }}
        </el-button>
        
        <el-tag v-else type="info" class="tag-limit-info">{{ t('cardEditor.tagLimit') }}</el-tag>
      </div>
    </div>
    
    <!-- Markdown提示（在Markdown模式下显示） -->
    <div class="markdown-tips" v-if="editorMode === 'markdown'">
      <h3>{{ t('markdown.tips.title') }}</h3>
      <div class="tips-grid">
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.headers.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.headers.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.textFormat.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.textFormat.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.lists.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.lists.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.quotesAndCode.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.quotesAndCode.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.linksAndImages.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.linksAndImages.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
        <div class="tip-item">
          <div class="tip-title">{{ t('markdown.tips.tables.title') }}</div>
          <div class="tip-content">
            <code v-for="(tip, index) in t('markdown.tips.tables.content')" :key="index">{{ tip }}</code>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.card-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f9f9f9;
}

/* 全屏模式 */
.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-color: white;
}

/* 顶部工具栏 */
.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-container {
  position: relative;
  border-radius: 4px;
  padding: 4px 8px;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.title-focused {
  border: 1px solid #dcdfe6;
  background-color: #fff;
}

.title-input {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  border: none;
  outline: none;
  width: 300px;
  background: transparent;
}

/* 桶名称输入框样式 */
.bucket-container {
  position: relative;
  border-radius: 4px;
  padding: 4px 8px;
  transition: all 0.2s;
  margin-left: 10px;
}

.bucket-select {
  width: 150px;
}

.save-status {
  font-size: 13px;
  color: #909399;
}

.start-time-container {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.start-time-display {
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 3px 8px;
  transition: all 0.2s;
}

.start-time-display:hover {
  background-color: #e6f1fc;
}

.start-time-placeholder {
  display: inline-block;
  width: 1px;
  height: 1px;
}

.date-time-picker-container {
  padding: 12px;
}

.date-time-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #303133;
}

/* 编辑器工具栏 */
.editor-toolbar {
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
}

.custom-toolbar {
  box-shadow: none !important;
}

/* 编辑器主体 */
.editor-body {
  flex: 1;
  overflow: hidden;
  background-color: white;
  margin: 16px 16px 8px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  position: relative; /* 添加相对定位用于占位符 */
}

.custom-editor {
  height: 100%;
  overflow-y: auto;
}

/* 标签区域样式 */
.tags-container {
  display: flex;
  padding: 8px 16px 16px;
  background-color: white;
  margin: 0 16px 16px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tags-label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-right: 12px;
  line-height: 32px;
}

.tags-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  flex: 1;
  position: relative;
}

.tag-item {
  margin-right: 0;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.tag-input {
  width: 150px;
  margin-right: 0;
}

.input-buttons {
  display: flex;
  gap: 2px;
}

.button-new-tag {
  height: 32px;
  padding: 0 12px;
  font-size: 12px;
  border-style: dashed;
}

.tag-limit-info {
  font-size: 12px;
  padding: 0 10px;
  height: 32px;
  line-height: 30px;
}

/* 颜色选择器样式 */
.color-picker-container {
  position: absolute;
  bottom: 40px;
  left: 50px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 12px;
  z-index: 100;
  width: 220px;
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.color-option {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.custom-color-input {
  margin-top: 8px;
  width: 100%;
}

.color-preview {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: transparent;
  transition: background-color 0.2s ease;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.selected {
  border-color: #333;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}

@media (prefers-color-scheme: dark) {
  .color-picker-container {
    background-color: #262626;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  }
  
  .color-option.selected {
    border-color: #fff;
  }
  
  .color-preview {
    border-color: #666;
  }
}

/* 占位符样式 */
.placeholder-arrow {
  position: absolute;
  left: 24px;
  top: 16px;
  display: flex;
  align-items: center;
  pointer-events: none;
  z-index: 100;
}

.arrow-text {
  color: #bfbfbf;
  font-size: 16px;
}

.cursor-placeholder {
  color: #333;
  font-size: 16px;
  animation: blink 1s infinite;
  margin-left: 2px;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 隐藏编辑器默认占位符 */
:deep(.w-e-text-placeholder) {
  display: none !important;
}

/* Markdown提示 */
.markdown-tips {
  margin: 0 16px 16px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.markdown-tips h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.tips-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

.tip-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
}

.tip-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.tip-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.tip-content code {
  background-color: #f5f7fa;
  padding: 4px 6px;
  border-radius: 4px;
  font-family: 'Menlo', 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  color: #476582;
}

:deep(.w-e-toolbar) {
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  padding: 0 8px !important;
}

:deep(.w-e-text-container) {
  border: none !important;
}

:deep(.w-e-text-container [data-slate-editor]) {
  padding: 16px 24px !important;
  text-align: left !important;
}

/* 针对暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .card-editor-container {
    background-color: #1a1a1a;
  }
  
  .editor-header, .editor-toolbar, .editor-body, .markdown-tips, .tags-container {
    background-color: #262626;
    border-color: #333;
  }
  
  .title-input {
    color: #e0e0e0;
  }
  
  .title-focused {
    border-color: #4c4c4c;
  }
  
  .save-status {
    color: #a0a0a0;
  }
  
  .tip-item {
    border-color: #3a3a3a;
  }
  
  .tip-title {
    color: #c0c0c0;
  }
  
  .tip-content code {
    background-color: #333;
    color: #9cdcfe;
  }
  
  .cursor-placeholder {
    color: #e0e0e0;
  }
  
  .tags-label {
    color: #c0c0c0;
  }
  
  .start-time-display {
    color: #e0e0e0;
    background-color: #363636;
  }
  
  .start-time-display:hover {
    background-color: #404040;
  }
  
  .date-time-title {
    color: #e0e0e0;
  }
}
</style>